<?php
namespace App\Libs\wrapper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class Platform extends Comm{
//////////////////////////////////////////////// 平台
////////////////////// 平台列表
	/**
	 * 平台列表--数据
	 * @param name 名称
	 * @param identifying 标识
	 */
	public function platform_list($data){
        $where = "p.state=1";
        // name 名称
        if(!empty($data['name'])){
            $where .= " and p.`name` like '%{$data['name']}%'";
        }
        // identifying 标识
        if(!empty($data['identifying'])){
            $where .= " and p.`identifying`='{$data['identifying']}'";
        }
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}
        
        $sql = "select SQL_CALC_FOUND_ROWS p.*
                    from platform p
                    where {$where}
                    order by p.Id desc {$limit}";
        $list = json_decode(json_encode(db::select($sql)),true);
		
		//// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
		$return['list']=$list;
        return $return;
    }
	
	/**
	 * 新增平台
	 * @param name 名称
	 * @param identifying 标识
	 * @logic 名称、标识唯一
	 */
	public function platform_add($data){
		// 名称、标识唯一
		$sql = "select `name`, `identifying`
					from platform
					where `name`='{$data['name']}' or `identifying`='{$data['identifying']}'";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($find)){
			if($find[0]['name'] == $data['name']){
				return '该平台名称已被使用';
			}else if($find[0]['identifying'] == $data['identifying']){
				return '该标识已被使用';
			}
		}
		
		//// 新增数据
		$field_arr = array('name', 'identifying');
		$field = '';
		$insert = '';
		foreach ($data as $k=>$v){
			if(in_array($k, $field_arr)){
				$field .= ",`{$k}`";
				$insert .= is_numeric($v) ? ",{$v}" : ",'{$v}'";
			}
		}
		$field = substr($field, 1);
		$insert = substr($insert, 1);
		
		$sql = "insert into platform({$field}) values ({$insert})";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
	}
	
	/**
	 * 编辑平台
	 * @param Id
	 * @parma name 名称
	 * @param identifying 标识
	 * @parma identifying_log 旧标识
	 * @logic 名称、标识唯一
	 */
	public function platform_update($data){
		// 名称、标识唯一
		$sql = "select `name`, `identifying`
					from platform
					where `Id`!={$data['Id']} and (`name`='{$data['name']}' or `identifying`='{$data['identifying']}')";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($find)){
			if($find[0]['name'] == $data['name']){
				return '该平台名称已被使用';
			}else if($find[0]['identifying'] == $data['identifying']){
				return '该标识已被使用';
			}
		}
		
		//// 验证是否已被绑定
		$set = "";
		// name 名称
		if(!empty($data['name'])){
			$set .= ", `name`='{$data['name']}'";
		}
		//identifying 标识
		if($data['identifying'] != $data['identifying_log']){
			// 修改标识，检查标识是否已被绑定
			$sql = "select `Id`
						from `spu`
						where platform_id={$data['Id']}";
			$find_p = json_decode(json_encode(db::select($sql)),true);
			if(empty($find_p)){
				// 未绑定可修改标识
				$set .= ",identifying='{$data['identifying']}'";
			}else{
				return '该平台已被绑定，不能修改标识';
			}
		}
		if(empty($set)){
			return '修改数据为空';
		}
		$set = substr($set, 1);
		
		$sql = "update platform
					set {$set}
					where `Id`={$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			Redis::Hdel('platform',$data['Id']);
			return 1;
		}else{
			return '编辑失败';
		}
	}
	
	/**
	 * 删除平台
	 * @param Id
	 */
	public function platform_del($data){
		// 删除平台，检查标识是否已被绑定
		$sql = "select `Id`
						from `spu`
						where platform_id={$data['Id']}";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($find)) {
			return '该平台已被绑定，不能删除';
		}
		
		$sql = "delete
					from `platform`
					where `Id`={$data['Id']}";
		$delete = db::delete($sql);
		if($delete){
			Redis::Hdel('platform',$data['Id']);
			return 1;
		}else{
			return '删除失败';
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 
 
 
 
 
	/*
	 * 删除任务消息
	 * @param Id 任务id
	 */
	public function task_del($data){
		// 删除任务信息、任务审核、任务节点、节点任务、任务消息、站内消息
		$sql = "delete t, te, tn, n, ts, ti
					from tasks t
					left join tasks_examine te on te.task_id = t.Id
					left join tasks_news tn on tn.task_id = t.Id
					inner join tasks_node n on n.task_id = t.Id
					inner join tasks_son ts on ts.task_id = t.Id
					left join tidings ti on ti.object_type=1 and ti.object_id=t.Id
					where t.`Id`={$data['Id']}";
		$del = db::delete($sql);
		if($del){
			return 1;
		}else{
			return '删除失败';
		}
	}
	
	/**
	 * 任务审核
	 * @parma Id 任务审核id
	 * @param task_id 任务id
	 * @param desc 审核描述
	 * @param state 状态：1.待审核、2.已同意、3.已拒绝
	 * @logic 修改审核（是否可审核、审核状态） --> 获取下个审核信息 --> 有：修改审核（是否可审核），发送站内消息给审核人；无修改任务（任务状态），触发任务
	 */
	public function tasks_examine($data){
		// 任务信息
		$sql = "select *
						from tasks
						where `Id`={$data['task_id']}
						limit 1";
		$task_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($task_find)){
			return '任务不存在';
		}
		
		db::beginTransaction();	//开启事务
		
		//当前时间
		$time = time();
		$time_now = date('Y-m-d H:i:s', $time);
		
		//// 修改审核（是否可审核、审核状态）
		$set = "is_examine=1, state={$data['state']}, time_sh='{$time_now}'";
		//desc 审核描述
		if(!empty($data['desc'])){
			$set .= ", `desc`='{$data['desc']}'";
		}
		$sql = "update tasks_examine
					set {$set}
					where `Id` = {$data['Id']}";
		$examine_update = db::update($sql);
		if(!$examine_update){
			db::rollback();// 回调
			return '修改审核失败--tasks_examine表';
		}
		
		//审核
		if($data['state'] == 3){
			//拒绝
			
			//修改任务状态
			$sql = "update tasks
						set state=2, time_examine='{$time_now}'
						where `Id` ={$data['task_id']}";
			$task_update = db::update($sql);
			if(!$task_update){
				db::rollback();// 回调
				return '修改任务状态失败--tasks表';
			}
			
			//发送站内消息给负责人
			$content = "任务：{$task_find[0]['name']}，审核被拒绝";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$task_find[0]['user_fz']}, '任务审核', '{$content}', {$data['task_id']}, 1, 1, '{$time_now}')";
			db::insert($sql);
		}else{
			//同意
			
			//// 获取下个审核信息
			$sql = "select *
						from tasks_examine
						where `task_id`={$data['task_id']} and `Id`>{$data['Id']}
						limit 1";
			$examine_next = json_decode(json_encode(db::select($sql)),true);
			
			//有：修改审核（是否可审核），发送站内消息给审核人；
			//无:修改任务（任务状态），触发任务
			if(count($examine_next) > 0){
				//有：修改审核（是否可审核），发送站内消息给审核人；
				$sql = "update tasks_examine
							set is_examine=2
							where `Id` = {$examine_next[0]['Id']}";
				$examine_update = db::update($sql);
				if(!$examine_update){
					db::rollback();// 回调
					return '修改任务状态失败--tasks表';
				}
				
				//发送站内消息给审核人
				$content = "任务：{$task_find[0]['name']} ，需要您审核，情尽快处理！";
				$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$examine_next[0]['user_id']}, '任务审核', '{$content}', {$data['task_id']}, 1, 1, now())";
				db::insert($sql);
			}else{
				//无:修改任务（任务状态），触发任务
				//修改任务状态
				$sql = "update tasks
							set state=3, time_examine='{$time_now}'
							where `Id` ={$data['task_id']}";
				$task_update = db::update($sql);
				if(!$task_update){
					db::rollback();// 回调
					return '修改任务状态失败--tasks表';
				}
				
				//发送站内消息给负责人
				$content = "任务：{$task_find[0]['name']}，审核已通过";
				$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$task_find[0]['user_fz']}, '任务审核', '{$content}', {$data['task_id']}, 1, 1, now())";
				db::insert($sql);
				
				//触发任务
				$arr = array();
				$arr['task_id'] = $data['task_id'];
				$task_trigger = $this->task_trigger($arr);
				if($task_trigger != 1){
					return $task_trigger;
				}
			}
		}
		
		db::commit();// 确认
		return 1;
	}
	
	/**
	 * 触发节点任务
	 * @param task_id 任务id
	 * @logic 获取节点、节点任务 --> 修改节点状态（进行中） --> 第一节点任务开启、发送消息
	 */
	public function task_trigger($data){
		if(empty($data['task_id'])){
			return 'task_id为空';
		}
		
		//获取节点
		$sql = "select *
                   from tasks_node
                   where `task_id`={$data['task_id']} and `state`=1
                   order by `Id` asc
                   limit 1";
		$node_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($node_find)){
			return '获取节点失败';
		}
		
		//当前时间
		$time = time();
		$time_now = date('Y-m-d H:i:s', $time);
		
		//修改节点状态（进行中）
		$sql = "update tasks_node
					set `state`=2, time_state='{$time_now}'
					where `Id`={$node_find[0]['Id']}";
		$node_update = db::update($sql);
		if(!$node_update){
			db::rollback();// 回调
			return '修改节点状态失败--tasks_node表';
		}
		
		//获取节点任务
		$sql = "select *
					from tasks_son
					where tasks_node_id={$node_find[0]['Id']} and f_id=0";
		$tasks_son_list = json_decode(json_encode(db::select($sql)),true);
		
		//第一节点任务开启、发送消息
		foreach ($tasks_son_list as $k=>$v){
			//第一节点任务开启
//			$time_end_yj = date('Y-m-d H:i:s', strtotime("+{$v['day_yj']} day", $time));
			$bb = $time + (3600 * 24 * $v['day_yj']);
			$time_end_yj = date('Y-m-d H:i:s', $bb);
			$sql = "update tasks_son
						set state=2, time_state='{$time_now}', time_end_yj='{$time_end_yj}'
						where `Id`={$v['Id']}";
			$tasks_son_update = db::update($sql);
			if(!$tasks_son_update){
				db::rollback();// 回调
				return '修改节点任务失败--tasks_son表';
			}
			
			//发送站内消息给审核人
			$content = "您有新的任务，情尽快处理！";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$v['user_id']}, '新任务', '{$content}', {$v['task_id']}, 1, 1, '{$time_now}')";
		    db::insert($sql);
		}
		
		return 1;
	}

////////////////////// 任务详情
	/**
	 * 任务详情
	 * @param task_id 任务id
	 * @logic 任务基本信息、审核信息、节点、节点任务
	 */
	public function task_info($data){
		//// 任务基本信息
		$sql = "select t.*, (select `account` from users where `Id`=t.user_fz) as account_fz
					from `tasks` t
					where t.Id = {$data['task_id']}";
		$task_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($task_find)){
			return '任务不存在';
		}
		
		//// 审核信息
		$sql = "select user_id
					from tasks_examine
					where task_id = {$data['task_id']}";
		$tasks_examine = json_decode(json_encode(db::select($sql)),true);
		
		//// 节点、节点任务
		$sql = "select n.Id as n_id, n.task_id as n_task_id, n.name as n_name, n.state as n_state,
						n.time_state as n_time_state, n.time_end as n_time_end, ts.*
					from tasks_node n
					inner join (select t.*, u.account, u.phone, u.heard_img
									from tasks_son t
									inner join users u on u.Id = t.user_id
								) ts on ts.tasks_node_id = n.Id
					where n.task_id={$data['task_id']}
					order by n_id asc";
		$tasks_node_list = json_decode(json_encode(db::select($sql)),true);
		if(empty($tasks_node_list)){
			return '任务节点不存在';
		}
		
		//处理数据
		$node = array();
		$node_ids = array();
		foreach ($tasks_node_list as $k=>$v){
			//所在位置
			$aa = array_search($v['n_id'], $node_ids);//array_search：变量是否在数组中，并返回所在位置
			//新增节点
			if($aa === false){
				$arr = array();
				$arr['Id'] = $v['n_id'];
				$arr['task_id'] = $v['n_task_id'];
				$arr['name'] = $v['n_name'];
				$arr['state'] = $v['n_state'];
				$arr['time_state'] = $v['n_time_state'];
				$arr['time_end'] = $v['n_time_end'];
				$arr['node_task_data'] = array();
				
				$node[] = $arr;
				$node_ids[] = $v['n_id'];
			}
			
			//新增节点任务
			$arr = array();
			$arr['Id'] = $v['Id'];
			$arr['task_id'] = $v['task_id'];
			$arr['tasks_node_id'] = $v['tasks_node_id'];
			$arr['f_id'] = $v['f_id'];
			$arr['task'] = $v['task'];
			$arr['user_id'] = $v['user_id'];
			$arr['day_yj'] = $v['day_yj'];
			$arr['state'] = $v['state'];
			$arr['feedback_type'] = $v['feedback_type'];
			$arr['feedback_content'] = $v['feedback_content'];
			$arr['time_state'] = $v['time_state'];
			$arr['time_end_yj'] = $v['time_end_yj'];
			$arr['time_end_sj'] = $v['time_end_sj'];
			$arr['create_time'] = $v['create_time'];
			
			$arr['account'] = $v['account'];
			$arr['phone'] = $v['phone'];
			$arr['heard_img'] = $v['heard_img'];
			
			//当前所在位置
			$bb = array_search($v['n_id'], $node_ids);
			$node[$bb]['node_task_data'][] = $arr;
		}
		
		$retuan = array();
		
		$retuan['basic'] = $task_find[0];
		$retuan['basic']['examine'] = $tasks_examine;
		$retuan['node'] = $node;
		return $retuan;
    }
	
	/**
	 * 编辑节点任务
	 * @param Id 节点任务id
	 */
	public function node_task_update($data){
		// 获取节点任务
		$sql = "select *
					from tasks_son
					where `Id` = {$data['Id']}";
		$tasks_son_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($tasks_son_find)){
			return '节点任务不存在';
		}else if($tasks_son_find[0]['state'] == 3){
			return '节点任务已完成，不能编辑';
		}else if($tasks_son_find[0]['state'] == 4){
			return '节点任务已放弃，不能编辑';
		}
		
		$set = '';
		//task 任务
		if(!empty($data['task'])){
			$set .= ",task='{$data['task']}'";
		}
		//user_id 执行人
		if(!empty($data['user_id'])){
			$set .= ",user_id={$data['user_id']}";
		}
		//day_yj 预计完成天数
		if(!empty($data['day_yj'])){
			//预计结束时间
			if($data['state'] != '1'){
//				$data['time_end_yj'] = date('Y-m-d H:i:s', strtotime("+{$data['day_yj']} day", strtotime($data['time_state'])));
				$bb = strtotime($data['time_state']) + (3600 * 24 * $data['day_yj']);
				$data['time_end_yj'] = date('Y-m-d H:i:s', $bb);;
				
				$set .= ",time_end_yj='{$data['time_end_yj']}'";
			}
			
			$set .= ",day_yj={$data['day_yj']}";
		}
		
		$set = substr($set, 1);
		$sql = "update tasks_son
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update === false){
			return '编辑失败';
		}
		
		// 发送站内消息    节点任务进行中，且执行人有更换
		if($tasks_son_find[0]['state']==2 && $tasks_son_find[0]['user_id']!=$data['user_id']){
			$content = "您有新的任务，情尽快处理！";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$data['user_id']}, '新任务', '{$content}', {$data['task_id']}, 1, 1, now())";
			db::insert($sql);
		}
		
		return $data;
	}
	
	/**
	 * 节点任务--（完成、放弃）
	 * @param Id 节点任务id
	 * @param state 状态：1.未开始、2.进行中、3.已完成、4.已放弃
	 * @param feedback_type 反馈类型：1.文字、2.图片、3.文件
	 * @param feedback_content 反馈内容
	 * @logic  1、检测是否已修改过状态
	 *         2、修改节点任务状态
	 *         3、该节点下是否还有任务没做完
	 *             未都完成：完
	 *             都已完成：修改节点状态、结束时间
	 *                      是否是最后一个节点
	 *                          是：结束时间、修改任务状态，发站内消息给负责人提示验收
	 *                          否：触发下一节点
	 */
	public function task_son_complete($data){
		//// 1、检测是否已修改过状态
		// 获取节点任务
		$sql = "select *
					from tasks_son
					where `Id` = {$data['Id']}";
		$tasks_son_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($tasks_son_find)){
			return '节点任务获取失败';
		}else if($tasks_son_find[0]['state'] == 3){
			return '该节点任务已完成';
		}else if($tasks_son_find[0]['state'] == 4){
			return '该节点任务已被放弃';
		}
		
		//当前时间
		$time = time();
		$time_now = date('Y-m-d H:i:s', $time);
		
		//// 修改节点任务：状态、反馈类型、反馈内容、实际结束时间
		$sql = "update tasks_son
					set `state`={$data['state']}, feedback_type={$data['feedback_type']}, feedback_content='{$data['feedback_content']}', time_end_sj='{$time_now}'
					where `Id` = {$data['Id']}";
		$tasks_son_update = db::update($sql);
		if(!$tasks_son_update){
			return '修改节点任务失败';
		}
		
		//// 该节点下是否还有任务没做完
		$sql = "select *
					from tasks_son
					where tasks_node_id = {$tasks_son_find[0]['tasks_node_id']} and `state` in (1,2)";
		$tasks_son_no = json_decode(json_encode(db::select($sql)),true);
		if(count($tasks_son_no) > 0){
			// 该节点还有未完成的节点任务
			return 1;
		}
		
		// 都已完成：修改节点状态、结束时间
		$sql = "update tasks_node
					set `state`=3, `time_end`='{$time_now}'
					where `Id` = {$tasks_son_find[0]['tasks_node_id']}";
		$tasks_node_update = db::update($sql);
		if(!$tasks_node_update){
			return '修改节点失败';
		}
		
		//// 是否是最后一个节点
		$sql = "select *
                   from tasks_node
                   where `task_id`={$tasks_son_find[0]['task_id']} and `state`=1
                   order by `Id` asc
                   limit 1";
		$node_find = json_decode(json_encode(db::select($sql)),true);
		if(count($node_find) > 0){
			// 否：触发下一节点
			//触发任务
			$arr = array();
			$arr['task_id'] = $tasks_son_find[0]['task_id'];
			$task_trigger = $this->task_trigger($arr);
			if($task_trigger != 1){
				return $task_trigger;
			}
			
		}else if(count($node_find) === 0){
			//// 是：结束时间、修改任务状态，发站内消息给负责人提示验收
			// 结束时间、修改任务状态
			$sql = "update tasks
						set `state`=4, `time_end`='{$time_now}'
						where `Id` = {$tasks_son_find[0]['task_id']}";
			$task_update = db::update($sql);
			if(!$task_update){
				return '修改任务失败';
			}
			
			// 发站内消息给负责人提示验收
			$sql = "select *
						from tasks
						where `Id` = {$tasks_son_find[0]['task_id']}";
			$task_find = json_decode(json_encode(db::select($sql)),true);
			
			$content = "任务：{$task_find[0]['name']}，请验收！";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$task_find[0]['user_fz']}, '任务验收', '{$content}', {$task_find[0]['Id']}, 1, 1, '{$time_now}')";
			db::insert($sql);
		}
		
		return 1;
	}
	
	/**
	 * 编辑任务
	 * @parma Id 任务id
	 * @param name 任务名称
	 * @param user_fz 负责人
	 * @Parma desc 任务描述
	 */
	public function task_update($data){
		$set = "";
		//name 任务名称
		if(!empty($data['name'])){
			// 验证唯一
			$sql = "select `Id`
						from `tasks`
						where `Id`!={$data['Id']} and `name` = '{$data['name']}'";
			$task_find = json_decode(json_encode(db::select($sql)),true);
			if(!empty($task_find)){
				return '任务名称已被使用，不能重复！';
			}
			
			$set .= ",`name`='{$data['name']}'";
		}
		//user_fz 负责人
		if(!empty($data['user_fz'])){
			$set .= ",`user_fz`={$data['user_fz']}";
		}
		//file_fj 附件
		if(!empty($data['file_fj'])){
			$set .= ",`file_fj`='{$data['file_fj']}'";
		}
		//desc 任务描述
		if(!empty($data['desc'])){
			$set .= ",`desc`='{$data['desc']}'";
		}
		
		if($set == ''){
			return '更新条件为空';
		}
		$set = substr($set, 1);
		
		$sql = "update tasks
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '更新失败';
		}
	}
	
	/**
	 * 任务消息
	 * @param task_id 任务id
	 */
	public function tasks_news_list($data){
		$where = "1=1";
		//task_id 任务id
		if(!empty($data['task_id'])){
			$where .= " and n.task_id={$data['task_id']}";
		}
		
		$sql = "select n.*, u_fs.account as account_fs, u_fs.heard_img as heard_img_fs,
						if(n.user_js, (select account from users where `Id`=n.user_js), '') as account_js
					from tasks_news n
					inner join users u_fs on u_fs.Id = n.user_fs
					where {$where}
					order by n.Id desc";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		$return['list']=$list;
		return $return;
	}
	
	/*
	 * 新增任务消息
	 * @param task_id 任务id
	 * @param task_name 任务名称
	 * @param user_fs 发送人
	 * @param user_js 接收人
	 * @param type 类型：1.文字、2.图片、3.文件
	 * @param content 内容
	 * @logic 新增任务消息
	 *          如有接收人，给接收人发送站内消息
	 */
	public function task_new_add($data){
		// 新增任务消息
		$field = 'create_time';
		$insert = 'now()';
		$arr = array('task_id', 'user_fs', 'user_js', 'type', 'content');
		foreach ($data as $k=>$v){
			if(in_array($k, $arr)){
				$field .= ",`{$k}`";
				$insert .= is_numeric($v) ? ",{$v}" : ",'{$v}'";
			}
		}
		
		$sql = "insert into tasks_news({$field}) values ({$insert})";
		$add = db::insert($sql);
		if(!$add){
			return '新增任务内消息失败';
		}
		
		// 如有接收人，给接收人发送站内消息
		if(!empty($data['user_js'])){
			$content = "任务：{$data['task_name']}，有发送给您的消息！";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values ({$data['user_fs']}, {$data['user_js']}, '任务内消息', '{$content}', {$data['task_id']}, 1, 1, now())";
			db::insert($sql);
		}
		
		return 1;
	}
	
	/*
	 * 删除任务消息
	 * @param Id 任务消息id
	 */
	public function task_new_del($data){
		// 获取任务消息
		$sql = "select *
					from tasks_news
					where `Id` = {$data['Id']}";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(empty($find)){
			return 1;
		}
		
		// 删除任务消息
		$sql = "delete
					from tasks_news
					where `Id`={$data['Id']}";
		$del = db::delete($sql);
		if(!$del){
			return '删除任务消息失败';
		}
		
		// 删除七牛云文件
		if(in_array($find[0]['type'], array('2', '3'))){
			$file_del = array();
			$file_url = explode('/', $find[0]['content']);
			$file_del[] = $file_url[(count($file_url) - 1)];
			//删除七牛云文件
			$Qiniu = new \App\Libs\wrapper\Qiniu();
			$Qiniu->file_del($file_del);
		}
		
		return 1;
	}
	
	/**
	 * 新增节点任务
	 * @logic 该节点是否已结束 --> 新增节点任务 --> 给执行人发送站内消息
	 */
	public function node_task_add($data){
		//// 该节点是否已结束
		$sql = "select `Id`, `state`
					from `tasks_node`
					where `Id` = {$data['tasks_node_id']}";
		$tasks_node_find = json_decode(json_encode(db::select($sql)),true);
		if(empty($tasks_node_find)){
			return '任务节点不存在';
		}else if($tasks_node_find[0]['state'] == 3){
			return '该任务节点已结束';
		}
		
		//// 新增节点任务
		$time = time();
		$time_now = date('Y-m-d H:i:s', $time);
		
		$filed = "`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`";
		$insert = "{$data['task_id']}, {$data['tasks_node_id']}, '{$data['task']}', {$data['user_id']}, {$data['day']}, '{$time_now}'";
		if($tasks_node_find[0]['state'] == 1){
			// 节点状态：未开始
			$filed .= ",`state`";
			$insert .= ",1";
		}else if($tasks_node_find[0]['state'] == 2){
			// 节点状态：进行中
			$time_end_yj = date('Y-m-d H:i:s', strtotime("+{$data['day']} day", $time));
			
			$filed .= ",`state`, `time_state`, `time_end_yj`";
			$insert .= ",2, '{$time_now}', '{$time_end_yj}'";
		}
		
		$sql = "insert into tasks_son({$filed}) values ({$insert})";
		$tasks_son_add = db::insert($sql);
		if(!$tasks_son_add){
			return '新增节点任务失败';
		}
		
		//发送站内消息给审核人
		if($tasks_node_find[0]['state'] == 2){
			$content = "您有新的任务，情尽快处理！";
			$sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
						values (0, {$data['user_id']}, '新任务', '{$content}', {$data['task_id']}, 1, 1, '{$time_now}')";
			db::insert($sql);
		}
		
		return 1;
	}
	
	/**
	 * 验收任务
	 * @param task_id 任务id
	 */
	public function task_determine($data){
		//// 该节点是否已结束
		$sql = "update tasks
		            set `state`=5, time_end=now()
		            where `Id` = {$data['task_id']}";
		$update = db::update($sql);
		if($update){
			return 1;
		}else{
			return '验收失败';
		}
	}

////////////////////// 待审核
	/**
	 * 待审核列表--数据
	 * @param name 任务名称
	 * @param user_fz_name 负责人名称
	 * @param state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
	 * @param type 类型：1.任务、2.任务模板
	 * @param create_time 创建时间
	 */
	public function task_audit_list($data){
		$where = "1=1";
		
		//name 任务名称
		if(isset($data['name'])){
			$where .= " and t.`name` like '%{$data['name']}%'";
		}
		//user_fz_name 负责人名称
		if(isset($data['user_fz_name'])){
			$where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
		}
		//user_cj_name 创建人名称
		if(isset($data['user_cj_name'])){
			$where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
		}
		//state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
		if(isset($data['state'])){
			$where .= " and t.`state`={$data['state']}";
		}
		//type 类型：1.任务、2.任务模板
		if(isset($data['type'])){
			$where .= " and t.`type`={$data['type']}";
		}
		//type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
		if(!empty($data['type_mb'])){
			$where .= " and t.`type_mb`={$data['type_mb']}";
		}
		//create_time 创建时间
		if (!empty($data['create_time'])) {
			$state_time = $data['create_time'][0] .' 00:00:00';
			$end_time = $data['create_time'][1] . ' 23:59:59';
			$where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
		}
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}
		
		$sql = "select SQL_CALC_FOUND_ROWS t.*, u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       inner join tasks_examine te on te.task_id=t.Id and te.is_examine=2 and te.user_id={$data['user_info']['Id']}
				       where {$where}
				       order by t.state asc,t.Id asc {$limit}";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		//// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
		$return['list']=$list;
		return $return;
	}
	
////////////////////// 新增任务页面
	/**
	 * 新增任务模板
	 * @param type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
	 * @parma name 任务模板名称
	 * @param user_fz 负责人
	 * @param desc 任务描述
	 * @param examine 审核人  数组
	 * @param node 节点、节点任务   数组
	 *              name 节点名称
	 *              node_task_data 节点任务     数组
	 *                      user_id 执行人
	 *                      day 预计完成天数
	 *                      task 任务
	 */
	public function task_template_add($data){
		//新增任务，验证唯一 --> 新增任务审核 --> 新增节点、节点任务
		//// 新增任务模板
		// 验证唯一
		$sql = "select `Id`
					from `tasks`
					where `name` = '{$data['name']}'";
		$task_find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($task_find)){
			return '名称已被使用，不能重复！';
		}
		
		// 新增任务模板
		db::beginTransaction();	//开启事务
		
		$arr = array();
		$arr['name'] = $data['name'];
		$arr['user_fz'] = $data['user_fz'];
		$arr['user_cj'] = isset($data['user_cj']) ? $data['user_cj'] : '';
		$arr['file_fj'] = isset($data['file_fj']) ? $data['file_fj'] : '';
		$arr['user_cs'] = empty($data['user_cs']) ? '' : implode(',',$data['user_cs']);;
		$arr['desc'] = isset($data['desc']) ? $data['desc'] : '';
		$arr['state'] = 1;
		$arr['type'] = 2;
		$arr['type_mb'] = $data['type_mb'];
		$arr['create_time'] = date('Y-m-d H:i:s', time());
		$task_add = db::table('tasks')->insertGetId($arr);
		if(!$task_add){
			db::rollback();// 回调
			return '新增任务失败--tasks表';
		}
		
		//// 新增节点、节点任务
		foreach ($data['node'] as $k=>$v){
			// 新增节点
			$arr = array();
			$arr['task_id'] = $task_add;
			$arr['name'] = $v['name'];
			$node_add = db::table('tasks_node')->insertGetId($arr);
			if(!$node_add){
				db::rollback();// 回调
				return '新增任务节点失败--tasks_node表';
			}
			
			// 节点任务
			$insert = "";
			foreach ($v['node_task_data'] as $k1=>$v1){
				$insert .= ",({$task_add}, {$node_add}, '{$v1['task']}', {$v1['user_id']}, {$v1['day_yj']}, now())";
			}
			$insert = substr($insert, 1);
			$sql = "insert into tasks_son(`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`) values {$insert}";
			$tasks_son_add = db::insert($sql);
			if(!$tasks_son_add){
				db::rollback();// 回调
				return '新增节点任务失败--tasks_son表';
			}
		}
		
		//// 新增任务审核
		if(isset($data['examine'])){
			$insert = "";
			foreach ($data['examine'] as $k=>$v){
				$insert .= ",({$task_add}, {$v}, 1)";
			}
			$insert = substr($insert, 1);
			$sql = "insert into tasks_examine(`task_id`, `user_id`, `is_examine`) values {$insert}";
			$tasks_examine_add = db::insert($sql);
			if(!$tasks_examine_add){
				db::rollback();// 回调
				return '新增任务审核失败--tasks_examine表';
			}
		}
		
		db::commit();// 确认
		return 1;
	}
	
	/**
	 * 编辑任务模板
	 * @param Id 任务模板id
	 * @param type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
	 * @parma name 任务模板名称
	 * @param user_fz 负责人
	 * @param desc 任务描述
	 * @param examine 审核人  数组
	 * @param node 节点、节点任务   数组
	 *              name 节点名称
	 *              node_task_data 节点任务     数组
	 *                      user_id 执行人
	 *                      day 预计完成天数
	 *                      task 任务
	 */
	public function task_template_update($data){
		// 验证唯一
		$sql = "select `Id`
					from `tasks`
					where `Id`!={$data['Id']} and `name` = '{$data['name']}'";
		$task_find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($task_find)){
			return '名称已被使用，不能重复！';
		}
		
		//开启事务
		db::beginTransaction();
		
		//// 更新任务信息
		if(empty($data['user_cs'])){
			$data['user_cs'] = '';
		}else{
			$data['user_cs'] = implode(',', $data['user_cs']);
		}
		$sql = "update tasks
					set `name`='{$data['name']}', `user_fz`={$data['user_fz']}, `desc`='{$data['desc']}', `user_cs`='{$data['user_cs']}', `file_fj`='{$data['file_fj']}', `type_mb`={$data['type_mb']}
					where `Id` = {$data['Id']}";
		$task_update = db::update($sql);
		if($task_update === false){
			return '更新任务信息失败';
		}
		
		//// 删除：任务审核、任务节点、节点任务
		$sql = "delete te, n, ts
					from tasks t
					left join tasks_examine te on te.task_id = t.Id
					inner join tasks_node n on n.task_id = t.Id
					inner join tasks_son ts on ts.task_id = t.Id
					where t.`Id`={$data['Id']}";
		$del = db::delete($sql);
		
		//// 新增节点、节点任务
		foreach ($data['node'] as $k=>$v){
			// 新增节点
			$arr = array();
			$arr['task_id'] = $data['Id'];
			$arr['name'] = $v['name'];
			$node_add = db::table('tasks_node')->insertGetId($arr);
			if(!$node_add){
				db::rollback();// 回调
				return '新增任务节点失败--tasks_node表';
			}
			
			// 节点任务
			$insert = "";
			foreach ($v['node_task_data'] as $k1=>$v1){
				$insert .= ",({$data['Id']}, {$node_add}, '{$v1['task']}', {$v1['user_id']}, {$v1['day_yj']}, now())";
			}
			$insert = substr($insert, 1);
			$sql = "insert into tasks_son(`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`) values {$insert}";
			$tasks_son_add = db::insert($sql);
			if(!$tasks_son_add){
				db::rollback();// 回调
				return '新增节点任务失败--tasks_son表';
			}
		}
		
		//// 新增任务审核
		if(isset($data['examine'])){
			$insert = "";
			foreach ($data['examine'] as $k=>$v){
				$insert .= ",({$data['Id']}, {$v}, 1)";
			}
			$insert = substr($insert, 1);
			$sql = "insert into tasks_examine(`task_id`, `user_id`, `is_examine`) values {$insert}";
			$tasks_examine_add = db::insert($sql);
			if(!$tasks_examine_add){
				db::rollback();// 回调
				return '新增任务审核失败--tasks_examine表';
			}
		}
		
		db::commit();// 确认
		return 1;
	}

////////////////////// 我的任务
	/**
	 * 我的任务列表--数据
	 * @param user_id 执行人
	 * @param task_name 任务名称
	 * @param task 任务描述
	 * @param time_end_yj 预计结束时间
	 */
	public function task_me($data){
		//// 获取任务
		$where = "1=1";
		//user_id 执行人
		if (!empty($data['user_id'])) {
			$where .= " and ts.`user_id`={$data['user_id']}";
		}
		//task_name 任务名称
		if(isset($data['task_name'])){
			$where .= " and t.`name` like '%{$data['task_name']}%'";
		}
		//task 任务描述
		if(isset($data['task'])){
			$where .= " and ts.`task` like '%{$data['task']}%'";
		}
		//time_end_yj 预计结束时间
		if (!empty($data['time_end_yj'])) {
			$state_time = $data['time_end_yj'][0] .' 00:00:00';
			$end_time = $data['time_end_yj'][1] . ' 23:59:59';
			$where .= " and ts.time_end_yj>='{$state_time}' and ts.time_end_yj<='{$end_time}'";
		}
		
		$sql = "select ts.*, t.name as task_name
				       from tasks_son ts
				       inner join tasks t on t.Id = ts.task_id
				       where {$where}
				       order by ts.time_end_yj asc";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		//// 处理数据
		$arr = array();
		$arr['overdue'] = array();//已逾期
		$arr['not_overdue'] = array();//未逾期
		$arr['abandon'] = array();//已放弃
		$arr['complete'] = array();//已完成
		
		if(!empty($list)){
			// 当前时间
			$time_now = date('Y-m-d H:i:s', time());
			foreach ($list as $k=>$v){
				if($v['state']==2 && $v['time_end_yj']<$time_now){
					//已逾期：状态 = 2、预计结束时间 < 当前时间
					$arr['overdue'][] = $v;
				}else if($v['state']==2 && $v['time_end_yj']>=$time_now){
					//未逾期：状态 = 2、预计结束时间 >= 当前时间
					$arr['not_overdue'][] = $v;
				}else if($v['state']==4){
					//已放弃：状态 = 4
					$arr['abandon'][] = $v;
				}else if($v['state']==3){
					//已完成：状态 = 3
					$arr['complete'][] = $v;
				}
			}
		}
		
		return $arr;
	}

////////////////////// 任务列表
	/**
	 * 任务定时器--数据
	 * @param name 定时器名称
	 * @param account_cj 创建人
	 * @param task_name 循环任务
	 * @param state 状态：1.未开始、2.运行中、3.暂停、4.结束
	 * @param create_time 创建时间
	 */
	public function task_timer($data){
		$where = "1=1";
		
		//name 定时器名称
		if(isset($data['name'])){
			$where .= " and tt.`name` like '%{$data['name']}%'";
		}
		//account_cj 创建人
		if(isset($data['account_cj'])){
			$where .= " and u.`account` like '%{$data['account_cj']}%'";
		}
		//task_name 循环任务
		if(isset($data['task_name'])){
			$where .= " and t.`name` like '%{$data['task_name']}%'";
		}
		//state 状态：1.未开始、2.运行中、3.暂停、4.结束
		if(isset($data['state'])){
			$where .= " and tt.`state`={$data['state']}";
		}
		//create_time 创建时间
		if (!empty($data['create_time'])) {
			$state_time = $data['create_time'][0] .' 00:00:00';
			$end_time = $data['create_time'][1] . ' 23:59:59';
			$where .= " and tt.create_time>='{$state_time}' and tt.create_time<='{$end_time}'";
		}
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}
		
		$sql = "select SQL_CALC_FOUND_ROWS tt.*, u.account as account_cj, t.name as task_name
					from tasks_timer tt
					inner join users u on u.Id = tt.user_id
					inner join tasks t on t.Id = tt.task_id
					where {$where}
				    order by tt.Id desc {$limit}";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		//// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
		$return['list']=$list;
		return $return;
	}
	
	/**
	 * 新增任务定时器
	 * @parma name 定时器名称
	 * @param user_id 创建人
	 * @param task_id 任务id
	 * @param desc 描述
	 * @param time_state 开始时间
	 * @param time_end 结束时间
	 * @param loop_type 循环类型：1.每天、2.每周、3.每月
	 * @param loop_time 循环时间
	 */
	public function task_timer_add($data){
		//新增定时器，验证唯一
		// 验证唯一
		$sql = "select `Id`
					from `tasks_timer`
					where `name` = '{$data['name']}'";
		$timer_find = json_decode(json_encode(db::select($sql)),true);
		if(!empty($timer_find)){
			return '定时器名称不能重复';
		}
		
		//// 新增任务
		$field_arr = array('name', 'user_id', 'task_id', 'desc', 'time_state', 'time_end', 'loop_type', 'loop_time');
		$data['loop_time'] = (!empty($data['loop_time'])) ? implode(',',$data['loop_time']) : '';
		$field = "create_time";
		$insert = "now()";
		foreach ($data as $k=>$v){
			if(in_array($k, $field_arr)){
				$field .= ",`{$k}`";
				$insert .= ",'{$v}'";
			}
		}
		
		$sql = "insert ignore into tasks_timer({$field}) values ({$insert})";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
	}
	
	/**
	 * 编辑任务定时器
	 * @param Id 任务任务定时器id
	 */
	public function task_timer_update($data){
		$set = "";
		if(!empty($data['loop_time'])){
			$data['loop_time'] = implode(',',$data['loop_time']);
		}
		$field_arr = array('name', 'task_id', 'desc', 'time_state', 'time_end', 'loop_type', 'loop_time', 'state');
		foreach ($data as $k=>$v){
			if(in_array($k, $field_arr)){
				// name 定时器名称
				if($k == 'name'){
					// 验证唯一
					$sql = "select `Id`
								from `tasks_timer`
								where `Id`!={$data['Id']} and `name`='{$data['name']}'";
					$timer_find = json_decode(json_encode(db::select($sql)),true);
					if(!empty($timer_find)){
						return '定时器名称不能重复';
					}
				}
				$set .= ",`{$k}`='{$v}'";
			}
		}
		if(empty($set)){
			return '修改数据为空';
		}
		$set = substr($set, 1);
		
		$sql = "update tasks_timer
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '编辑失败';
		}
	}
	
	/*
	 * 删除任务定时器
	 * @param Id 任务定时器id
	 */
	public function task_timer_del($data){
		$sql = "delete
					from tasks_timer
					where `Id`={$data['Id']}";
		$del = db::delete($sql);
		if($del){
			return 1;
		}else{
			return '删除失败';
		}
	}
	
	/**
	 * 触发定时器
	 */
	public function timer_trigger(){
		////获取定时器（1.未开始、2.运行中、3.暂停）
		$sql = "select *
					from `tasks_timer`
					where `state` != 4";
		$timer_list = json_decode(json_encode(db::select($sql)),true);
		if(empty($timer_list)){
			return 1;
		}
		
		// 时间  strtotime("2020-10-1")
		$time = time();
		$time_now = date('Y-m-d', $time);//当天时间
		$week = date("w", $time);//星期几
		$day = date("j", $time);//几号
		
		//开启事务
		db::beginTransaction();
		
		//// 修改状态、创建任务
		foreach ($timer_list as $k=>$v){
			
			$set = '';
			$is_add = 0;
			
			if($v['state']==1 && $time_now>=$v['time_state']){
				// 未开始  --》 运行中：修改状态、新增任务
				$set .= "`state`=2";
				
				if($v['loop_type'] == 1){
					//每天
					$is_add = 1;
				}else if($v['loop_type']==2){
					//每周
					$loop_time = explode(",", $v['loop_time']);
					if(in_array($week, $loop_time)){
						$is_add = 1;
					}
				}else if($v['loop_type']==3){
					//每月
					$loop_time = explode(",", $v['loop_time']);
					if(in_array($day, $loop_time)){
						$is_add = 1;
					}
				}
			}else if(($v['state']==2 || $v['state']==3) && $v['time_end']!='0000-00-00' && $time_now>$v['time_end']){
				// 运行中  --》 结束：修改状态
				$set .= "`state`=4";
			}else if($v['state']==2  && $time_now>=$v['time_state'] && ($time_now<=$v['time_end'] || $v['time_end']=='0000-00-00')){
				// 继续运行：新增任务
				if($v['loop_type'] == 1){
					//每天
					$is_add = 1;
				}else if($v['loop_type']==2){
					//每周
					$loop_time = explode(",", $v['loop_time']);
					if(in_array($week, $loop_time)){
						$is_add = 1;
					}
				}else if($v['loop_type']==3){
					//每月
					$loop_time = explode(",", $v['loop_time']);
					if(in_array($day, $loop_time)){
						$is_add = 1;
					}
				}
			}
			
			//// 修改状态
			if(!empty($set)){
				$sql = "update tasks_timer
							set {$set}
							where `Id` = {$v['Id']}";
				$timer_update = db::update($sql);
				if(!$timer_update){
					db::rollback();// 回调
				}
			}
			
			//// 创建任务
			if($is_add == 1){
				//获取任务详情
				$arr = array();
				$arr['task_id'] = $v['task_id'];
				$task_info = $this->task_info($arr);
				//  处理数据
				// 名称
				$task_info['basic']['name'] = $task_info['basic']['name']. '_' . date('YmdHis', time());
				// 审核人
//				var_dump(empty($task_info['basic']['examine']));exit;
				if(!empty($task_info['basic']['examine'])){
					$examine = array();
					foreach ($task_info['basic']['examine'] as $k=>$v){
						$examine[] = $v['user_id'];
					}
					$task_info['basic']['examine'] = $examine;
				}
				// 抄送人
				if(!empty($task_info['basic']['user_cs'])){
					$task_info['basic']['user_cs'] = explode(",", $task_info['basic']['user_cs']);
				}
				// 调用接口新增
				$arr = $task_info['basic'];
				$arr['node'] = $task_info['node'];
				$task_add = $this->task_add($arr);
				if($task_add != 1){
					db::rollback();// 回调
				}
			}
			
			db::commit();// 确认
		}
		
		return 1;
	}
	
	
	
	
	
	
	
	
	
	
	
	
}//结束符